package com.sinsz.common.util;

import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

/**
 * 请求工具
 * @author chenjianbo
 */
public final class RequestUtils {

    /**
     * 获取流中的参数
     * @param request
     * @return
     */
    public synchronized static String requestBody(HttpServletRequest request) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            InputStream is = request.getInputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            String result = new String(baos.toByteArray(),"UTF-8");
            return StringUtils.isEmpty(result) ? "" : result;
        } catch (IOException ignored) {
        }
        return "";
    }

    /**
     * 获取常规参数
     * @param request
     * @return
     */
    public synchronized static Map<String, String[]> requestParams(HttpServletRequest request) {
        return request.getParameterMap();
    }


}
